package com.mofeng.myshop.until.component;

import com.mofeng.myshop.until.Constants;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Component
public class CookieUtils {
    @Value("${cookie.domain}")
    private String domain;
    private final int default_age = Constants.Times.MONTH * 2;

    /**
     * 设置Cookie值
     *
     * @param key
     * @param value
     */
    public void setCookie(String key, String value) {
        setCookie(key, value, default_age);
    }

    public void setCookie(String key, String value, int age) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = requestAttributes.getResponse();
        Cookie cookie = new Cookie(key, value);
        cookie.setPath("/");
        cookie.setMaxAge(age);
        cookie.setDomain(domain);//默认返回当前服务器的ip
        response.addCookie(cookie);
    }

    /**
     * 删除Cookie值
     *
     * @param cookieKey
     */
    public void deleteCookie(String cookieKey) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = requestAttributes.getResponse();
        setCookie(cookieKey, null, 0);
    }

    /**
     * 获取Cookie值
     *
     * @param cookieKey
     * @return 对应的tokenKey值
     */
    public String getCookie(String cookieKey) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (cookieKey.equals(cookie.getName())) {
                return cookie.getValue();
            }
        }
        return null;
    }
}
